package com.OnTimeTeam.OnTime;


import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Calendar;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.PowerManager;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;


/******************************************************************************
 * ClassName: RemindersCollection (Activity class)
 * MoreAbout: This is the main screen the user see.
 * This activity present the reminders-list to the user.
 *****************************************************************************/
public class RemindersCollection extends Activity {
	
	private int backPressed;

	protected PowerManager.WakeLock mWakeLock;
	private TextView todayIs;
	private TextView timeToNextAlarm;
	private Button smartModeButton; // Button for smart-mode
	private Button regularModeButton; //Button for regular-mode
	private Button quickModeButton; //Button for quick-mode
	
	
	private ListView remindersList; //ListView object for the reminders
	private RemindersList adapter;
	
	private ArrayList<AlarmFeatures> alarmsArray; //array with details about existing alarms
	private ArrayList<String> items;
	
	
	private TextView quickNapMins;
	private SeekBar quickNapTimePicker;
	
	private String remindersFilePath;
	
	private TextView textMessage;
	private Toast toast;
	
	///////////////////
	//The first method which is activated in this activity
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.reminders); //View from file "res/layouts/reminders.xml"

		final LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		final View toastView = inflater.inflate(R.layout.costum_toast,null);
		textMessage = (TextView)toastView.findViewById(R.id.addressConfirmation);

		toast = new Toast(RemindersCollection.this);
		toast.setView(toastView);
		toast.setGravity(Gravity.BOTTOM|Gravity.CENTER, 0, 150);
		toast.setDuration(Toast.LENGTH_SHORT);
		
		
		backPressed = 0;
		
		remindersFilePath = getApplicationContext().getFilesDir().getPath().toString() + "/reminders.xml";
					
		//RemindersIO.initializeRemindersFile(remindersFilePath);
		
		todayIs = (TextView) findViewById(R.id.todayIs);
		
		switch(Calendar.getInstance().get(Calendar.DAY_OF_WEEK)){
		case Calendar.SUNDAY:
			todayIs.setText(getResources().getString(R.string.today_is_sunday));
			break;
		case Calendar.MONDAY:
			todayIs.setText(getResources().getString(R.string.today_is_monday));
			break;
		case Calendar.TUESDAY:
			todayIs.setText(getResources().getString(R.string.today_is_tuesday));
			break;
		case Calendar.WEDNESDAY:
			todayIs.setText(getResources().getString(R.string.today_is_wednesday));
			break;				
		case Calendar.THURSDAY:
			todayIs.setText(getResources().getString(R.string.today_is_thursday));
			break;				
		case Calendar.FRIDAY:
			todayIs.setText(getResources().getString(R.string.today_is_friday));
			break;
		case Calendar.SATURDAY:
			todayIs.setText(getResources().getString(R.string.today_is_saturday));
			break;					
		}
		
		//allocate the class objects
		smartModeButton = (Button) findViewById(R.id.smartButton);
		regularModeButton = (Button) findViewById(R.id.regularButton);
		quickModeButton = (Button) findViewById(R.id.quick);
		timeToNextAlarm = (TextView)findViewById(R.id.nextAlarm);
		remindersList = (ListView)findViewById(R.id.remindersList);
		
		
		
		
		Animation myFadeInAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_in);
		remindersList.setAnimation(myFadeInAnimation);
		
		Animation growFromBottomAnimation = AnimationUtils.loadAnimation(this, R.anim.grow_from_bottom1);

		regularModeButton.setAnimation(growFromBottomAnimation);
		smartModeButton.setAnimation(growFromBottomAnimation);
		quickModeButton.setAnimation(growFromBottomAnimation);

		
		
		alarmsArray = new ArrayList<AlarmFeatures>();
		
		//define what happens when clicking the Quick-Nap button
		quickModeButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {

				final LayoutInflater inflater = (LayoutInflater) RemindersCollection.this.getSystemService(LAYOUT_INFLATER_SERVICE);
				
				View quickLayout = inflater.inflate(R.layout.quick_nap_time_picker, null);
				quickNapMins = (TextView)quickLayout.findViewById(R.id.minutes);
				quickNapTimePicker = (SeekBar)quickLayout.findViewById(R.id.ttoSeekBar);

				Button saveButton = (Button)quickLayout.findViewById(R.id.bSave);
				Button cancelButton = (Button)quickLayout.findViewById(R.id.bCancel);


				final Dialog quickNapDialog = new Dialog(RemindersCollection.this, R.style.GrowBottom);
				quickNapDialog.setContentView(quickLayout);
				quickNapDialog.setCancelable(true);
				quickNapDialog.setTitle(getResources().getString(R.string.quickButton));
				
				
				cancelButton.setOnClickListener(new View.OnClickListener() {
					public void onClick(View v) {
						quickNapDialog.dismiss();
					}
				});
				
				//Save QuickNap alarm
				saveButton.setOnClickListener(new View.OnClickListener() {
					public void onClick(View v) {
                    	updateAlarmsAfterAddition(SetQuickNap.setQuickNap(quickNapTimePicker.getProgress() + 3, getApplicationContext()));
                    	quickNapDialog.dismiss();
					}
				});
				
				
				
				quickNapMins.setText("30" + " " + getResources().getString(R.string.minutes));
				
				
				quickNapTimePicker.setMax(57);
				quickNapTimePicker.setProgress(27);
				quickNapTimePicker.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
					
			        public void onStopTrackingTouch(SeekBar seekBar) {
			        }

			        public void onStartTrackingTouch(SeekBar seekBar) {
			        }

			        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
			        	
			        	quickNapMins.setText(Integer.toString(progress + 3) + " " + getResources().getString(R.string.minutes));
			        }
			    });

				quickNapDialog.show();

			}
		});
		
		
		//define what happens when clicking the button 'smartModeButton'
		smartModeButton.setOnClickListener(new View.OnClickListener() {
			
			//Create new smart-alarm
			public void onClick(View v) {
				
				if(isNetworkAvailable()){
					//Create Intent object
					Intent newAlarmIntent = new Intent(RemindersCollection.this, SetSmart.class);
					
					//put boolean value to tell us later we want to create a brand-new alarm and not edit an existing one
					newAlarmIntent.putExtra("isNewAlarm", true);
					
					finish();
					startActivity(newAlarmIntent);
					overridePendingTransition(R.anim.grow_from_top, R.anim.fade_out);
				}
				else {//Network is not available
					textMessage.setText(getResources().getString(R.string.verifyNetworkConnection));
					toast.show();
				}

			}
		});
		
		//define what happens when clicking the button 'regularModeButton'
		regularModeButton.setOnClickListener(new View.OnClickListener() {
			
			//create new regular alarm
			public void onClick(View v) {
				
				//Create Intent object
				Intent newAlarmIntent = new Intent("com.OnTimeTeam.OnTime.REGULARALARM");
				
				//put boolean value to tell us later we want to create a brand-new alarm and not edit an existing one
				newAlarmIntent.putExtra("isNewAlarm", true);
				
				finish();
				startActivity(newAlarmIntent);//start the activity which creates the alarm
				overridePendingTransition(R.anim.grow_from_top, R.anim.fade_out);
				
				
			}
		});
		
		
		
		
		
		//get all alarms
		alarmsArray = RemindersIO.getAllAlarms(this.remindersFilePath);
		items = new ArrayList<String>();
		ArrayList<AlarmFeatures> alarmsOn = new ArrayList<AlarmFeatures>();
		
        for(int i = 0; i < alarmsArray.size(); ++i) {
        	if(alarmsArray.get(i).getSortOfAlarm().equals("Smart"))
        		items.add("SMART_ITEM");
        	else if(alarmsArray.get(i).getSortOfAlarm().equals("Quick"))
        		items.add("QUICK_ITEM");
        	else
        		items.add("REGULAR_ITEM");
        	
        	if(alarmsArray.get(i).getStatus().equals("On"))
        		alarmsOn.add(alarmsArray.get(i));
        }
        
        NotifyAtBootReceiver.logAllAlarms(alarmsArray);
        
        if(alarmsOn.size() > 0) {
        	String notification = NotificationService.getClosestAlarmString(alarmsOn, remindersFilePath);
        	notification = notification.replace("Next alarm set for", getResources().getString(R.string.nextAlarmSetFor));
        	notification = notification.replace("Sun,", getResources().getString(R.string.sunQ));
        	notification = notification.replace("Mon,", getResources().getString(R.string.monQ));
        	notification = notification.replace("Tue,", getResources().getString(R.string.tueQ));
        	notification = notification.replace("Wed,", getResources().getString(R.string.wedQ));
        	notification = notification.replace("Thu,", getResources().getString(R.string.thuQ));
        	notification = notification.replace("Fri,", getResources().getString(R.string.friQ));
        	notification = notification.replace("Sat,", getResources().getString(R.string.satQ));
        	notification = notification.replace("Today,", getResources().getString(R.string.todayQ));

        	if(!notification.equals(timeToNextAlarm.getText().toString())){
	        	timeToNextAlarm.setText(notification);
	        	timeToNextAlarm.setVisibility(View.VISIBLE);
	        	timeToNextAlarm.startAnimation(myFadeInAnimation);
        	}
        }
        else {
        	timeToNextAlarm.setText("");
        	timeToNextAlarm.setVisibility(View.GONE);
        }
        
		//create adapter for the list of reminders
		adapter = new RemindersList(this,R.layout.reminder_smart_item, alarmsArray, items, getApplicationContext(), getBaseContext(), timeToNextAlarm);
		
		//set the adapter on the reminders-List-View
		remindersList.setAdapter(adapter);
		remindersList.setTextFilterEnabled(true);
		
		remindersList.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View v, int index, long id) {

				if(alarmsArray.get(index).getSortOfAlarm().equals("Regular")){
					
					//Create Intent object to SetRegularAlarm
					Intent newAlarmIntent = new Intent("com.OnTimeTeam.OnTime.REGULARALARM");
					
					//save all alarm features in the intent in order to present to the user in the next screen
					newAlarmIntent.putExtra("label", alarmsArray.get(index).getLabel());
					newAlarmIntent.putExtra("index", alarmsArray.get(index).getIndex());
					newAlarmIntent.putExtra("id", alarmsArray.get(index).getID());
					newAlarmIntent.putExtra("days", alarmsArray.get(index).getDaysToRepeat());
					newAlarmIntent.putExtra("daysIDS", alarmsArray.get(index).getDaysIDS());
					newAlarmIntent.putExtra("hour", alarmsArray.get(index).getHour());
					newAlarmIntent.putExtra("minute", alarmsArray.get(index).getMinute());
					
					newAlarmIntent.putExtra("vibration", alarmsArray.get(index).getVibration());
					newAlarmIntent.putExtra("volume", alarmsArray.get(index).getVolume());
					newAlarmIntent.putExtra("snoozeInterval", alarmsArray.get(index).getSnoozeInterval());
					newAlarmIntent.putExtra("snoozeRepeat", alarmsArray.get(index).getSnoozeRepeat());
					newAlarmIntent.putExtra("tune", alarmsArray.get(index).getTune());
					
					
					//put boolean value to tell SetNewAlarm activity we want edit an existing alarm
					newAlarmIntent.putExtra("isNewAlarm", false);
					//start the activity which creates the alarm
					finish();
					startActivity(newAlarmIntent);
					overridePendingTransition(R.anim.grow_from_top, R.anim.fade_out);
				}
				else if(alarmsArray.get(index).getSortOfAlarm().equals("Smart")){
					
					if(isNetworkAvailable()) {
						
						//Create Intent object to SetSmartAlarm
						Intent newAlarmIntent = new Intent("com.OnTimeTeam.OnTime.SMARTALARM");
						
						//save all alarm features in the intent in order to present to user in the next screen
						newAlarmIntent.putExtra("label", alarmsArray.get(index).getLabel());
						newAlarmIntent.putExtra("index", alarmsArray.get(index).getIndex());
						newAlarmIntent.putExtra("id", alarmsArray.get(index).getID());
						newAlarmIntent.putExtra("days", alarmsArray.get(index).getDaysToRepeat());
						newAlarmIntent.putExtra("daysIDS", alarmsArray.get(index).getDaysIDS());
						newAlarmIntent.putExtra("hour", alarmsArray.get(index).getHour());
						newAlarmIntent.putExtra("minute", alarmsArray.get(index).getMinute());
						
						newAlarmIntent.putExtra("vibration", alarmsArray.get(index).getVibration());
						newAlarmIntent.putExtra("volume", alarmsArray.get(index).getVolume());
						newAlarmIntent.putExtra("snoozeInterval", alarmsArray.get(index).getSnoozeInterval());
						newAlarmIntent.putExtra("snoozeRepeat", alarmsArray.get(index).getSnoozeRepeat());
						newAlarmIntent.putExtra("tune", alarmsArray.get(index).getTune());
						
						//set special features
						newAlarmIntent.putExtra("origin", ((SmartAlarmFeatures)alarmsArray.get(index)).getOrigin());
						newAlarmIntent.putExtra("destination", ((SmartAlarmFeatures)alarmsArray.get(index)).getDest());
						newAlarmIntent.putExtra("tto",((SmartAlarmFeatures)alarmsArray.get(index)).getTTO());
						newAlarmIntent.putExtra("transport",((SmartAlarmFeatures)alarmsArray.get(index)).getTransport());
						
						newAlarmIntent.putExtra("arrivalHour",((SmartAlarmFeatures)alarmsArray.get(index)).getArrivalHour());
						newAlarmIntent.putExtra("arrivalMinute",((SmartAlarmFeatures)alarmsArray.get(index)).getArrivalMinute());
						
						//put boolean value to tell SetNewAlarm activity we want edit an existing alarm
						newAlarmIntent.putExtra("isNewAlarm", false);
						
						
						if(((SmartAlarmFeatures)alarmsArray.get(index)).getTransport().equals("Transit"))
						{
							newAlarmIntent.putExtra("roadsQ",(TransitRoadsQuery)((SmartAlarmFeatures)alarmsArray.get(index)).getRoadsQ());
							newAlarmIntent.putExtra("track",(Track)((SmartAlarmFeatures)alarmsArray.get(index)).getTrack());
						}
						//start the activity which creates the alarm
						finish();
						startActivity(newAlarmIntent);
						
						overridePendingTransition(R.anim.grow_from_top, R.anim.fade_out);
					
					}
					else {
						textMessage.setText(getResources().getString(R.string.verifyNetworkConnection));
						toast.show();
					}
				}
				else { //Quick Alarm
					
					final int i = index;
					
					final LayoutInflater inflater = (LayoutInflater) RemindersCollection.this.getSystemService(LAYOUT_INFLATER_SERVICE);
					
					View quickLayout = inflater.inflate(R.layout.quick_nap_time_picker, null);
					quickNapMins = (TextView)quickLayout.findViewById(R.id.minutes);
					quickNapTimePicker = (SeekBar)quickLayout.findViewById(R.id.ttoSeekBar);

					Button saveButton = (Button)quickLayout.findViewById(R.id.bSave);
					Button cancelButton = (Button)quickLayout.findViewById(R.id.bCancel);

					final Dialog quickNapDialog = new Dialog(RemindersCollection.this, R.style.GrowBottom);
					quickNapDialog.setContentView(quickLayout);
					quickNapDialog.setCancelable(true);
					quickNapDialog.setTitle(getResources().getString(R.string.quickButton));
					
					
					cancelButton.setOnClickListener(new View.OnClickListener() {
						public void onClick(View v) {
							quickNapDialog.dismiss();
						}
					});
					
					saveButton.setOnClickListener(new View.OnClickListener() {
						public void onClick(View v) {
							
							//updateAlarmsAfterAddition();
                        	
							SetQuickNap.updateWithNewTime(alarmsArray.get(i), quickNapTimePicker.getProgress()+3, getApplicationContext(),i);
							
				            Intent notifyService = new Intent("com.OnTimeTeam.OnTime.NotificationService");
				            startService(notifyService);
							
				            adapter.notifyDataSetChanged();
							
							
				            setTimeToNextAlarm();
				            
                        	//restart the activity in order to refresh alarms-list
                        	//Intent savedIntent = new Intent(RemindersCollection.this, MainActivity.class);
                        	//finish();
                        	quickNapDialog.dismiss(); //Dismiss the dialog box
                        	//startActivity(savedIntent);
						}
					});


					
					quickNapMins.setText(alarmsArray.get(index).getQuickInterval() + " " + getResources().getString(R.string.minutes));
					

					quickNapTimePicker.setMax(57);
					quickNapTimePicker.setProgress(Integer.valueOf(alarmsArray.get(index).getQuickInterval())-3);
					quickNapTimePicker.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
						
				        public void onStopTrackingTouch(SeekBar seekBar) {
				        }

				        public void onStartTrackingTouch(SeekBar seekBar) {
				        }

				        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
				        	
				        	quickNapMins.setText(Integer.toString(progress + 3) + " " + getResources().getString(R.string.minutes));

				        }
				    });

					quickNapDialog.show();
				}
			}
		});
		
		
		remindersList.setOnItemLongClickListener(new OnItemLongClickListener() {

			public boolean onItemLongClick(AdapterView<?> lvAdapter, View reminderView,
					final int reminderIndex, long id) {
				
				ArrayList<Boolean> items = new ArrayList<Boolean>();
				items.add(true); items.add(true); items.add(true);
				if(alarmsArray.get(reminderIndex).getSortOfAlarm().equals("Smart")) {
					items.add(true);
					items.add(true);
				}
				
				//custom dialog
				final Dialog dialog = new Dialog(RemindersCollection.this, R.style.GrowBottom);
				dialog.setContentView(R.layout.string_list);
				dialog.setTitle(getResources().getString(R.string.alarmOptions));
	 
				//set the custom dialog components - text, image and button
				ListView optionsList = (ListView) dialog.findViewById(R.id.optionsList);
	 
				//Define what happens when clicking an item in the List-view
				optionsList.setOnItemClickListener(new OnItemClickListener() {

					public void onItemClick(AdapterView<?> arg0, View v, int optionIndex, long id) {
						switch(optionIndex){
							case 0:
								
								View currentView = remindersList.getChildAt(reminderIndex);
								ImageView onOrOff = null;
								
								if(currentView != null)
									onOrOff = (ImageView)currentView.findViewById(R.id.toggleButton1);
								
			        			if(alarmsArray.get(reminderIndex).getStatus().equals("On")) { //alarm is On - so we need to turn it Off
			        				
			        				if(onOrOff != null)
			        					onOrOff.setImageResource(R.drawable.alarm_off);
			        				
			        				//Change the alarm status in the xml file from "On" to "Off"
			        				RemindersIO.changeAlarmStatus(remindersFilePath, Integer.toString(reminderIndex), "Off");

			        				//Cancel the alarm through alarm-manager
			        				AlarmSetter.cancelExistingAlarm(alarmsArray.get(reminderIndex), getApplicationContext());
			        				
			        				//set alarm status "Off"
			        				alarmsArray.get(reminderIndex).setStatus("Off");
			        				
			        				
			        				
			        				//Handle snooze situation
			        				String snoozeID = RemindersIO.getSnoozeAlarmSign(alarmsArray.get(reminderIndex).getID(), remindersFilePath).split(",")[0];
			        				if(!snoozeID.equals("None")){
			        					
			        					AlarmFeatures tmpAF = new AlarmFeatures();
			        					tmpAF.setDaysIDS(snoozeID);
			        					AlarmSetter.cancelExistingAlarm(tmpAF, getApplicationContext());
			        					
			        					RemindersIO.changeSnoozeSign(alarmsArray.get(reminderIndex).getID(), remindersFilePath, "None");
			        					
			        				}
			        				
			        				
			        			} 
			        			else {// alarm is off - so we need to turn it On
			        				
			        				if(onOrOff != null)
			        					onOrOff.setImageResource(R.drawable.alarm_active);
			        				
			        				//Change the alarm status in the xml file from "Off" to "On"
			        				RemindersIO.changeAlarmStatus(remindersFilePath, Integer.toString(reminderIndex), "On");
			        			
			        				
				        			if(alarmsArray.get(reminderIndex).getSortOfAlarm().equals("Quick"))
				        				SetQuickNap.updateTime(alarmsArray.get(reminderIndex), getApplicationContext(), reminderIndex);
			        				
			        				//Set the alarm again with alarm-manager
			        				//AlarmSetter.setBackAlarm(alarmsArray.get(reminderIndex), getApplicationContext(), getBaseContext()); 
			        				
			        				//set alarm status "On"
			        				alarmsArray.get(reminderIndex).setStatus("On");
			        			}
			        			
		        	            Intent notifyService = new Intent("com.OnTimeTeam.OnTime.NotificationService");
		        	            startService(notifyService);
			        			
			        			adapter.notifyDataSetChanged();
			        			
			        			setTimeToNextAlarm();
			        			
								break;
							case 1:
								
								if(alarmsArray.get(reminderIndex).getSortOfAlarm().equals("Regular")){
									
									//Create Intent object to SetRegularAlarm
									Intent newAlarmIntent = new Intent("com.OnTimeTeam.OnTime.REGULARALARM");
									
									//save all alarm features in the intent in order to present to the user in the next screen
									newAlarmIntent.putExtra("label", alarmsArray.get(reminderIndex).getLabel());
									newAlarmIntent.putExtra("index", alarmsArray.get(reminderIndex).getIndex());
									newAlarmIntent.putExtra("id", alarmsArray.get(reminderIndex).getID());
									newAlarmIntent.putExtra("days", alarmsArray.get(reminderIndex).getDaysToRepeat());
									newAlarmIntent.putExtra("daysIDS", alarmsArray.get(reminderIndex).getDaysIDS());
									newAlarmIntent.putExtra("hour", alarmsArray.get(reminderIndex).getHour());
									newAlarmIntent.putExtra("minute", alarmsArray.get(reminderIndex).getMinute());
									
									newAlarmIntent.putExtra("vibration", alarmsArray.get(reminderIndex).getVibration());
									newAlarmIntent.putExtra("volume", alarmsArray.get(reminderIndex).getVolume());
									newAlarmIntent.putExtra("snoozeInterval", alarmsArray.get(reminderIndex).getSnoozeInterval());
									newAlarmIntent.putExtra("snoozeRepeat", alarmsArray.get(reminderIndex).getSnoozeRepeat());
									newAlarmIntent.putExtra("tune", alarmsArray.get(reminderIndex).getTune());
									
									//put boolean value to tell SetNewAlarm activity we want edit an existing alarm
									newAlarmIntent.putExtra("isNewAlarm", false);
									//start the activity which creates the alarm
									finish();
									startActivity(newAlarmIntent);
									overridePendingTransition(R.anim.grow_from_top, R.anim.fade_out);
								}
								else if(alarmsArray.get(reminderIndex).getSortOfAlarm().equals("Smart")){
									
									if(isNetworkAvailable()) {
										//Create Intent object to SetSmartAlarm
										Intent newAlarmIntent = new Intent("com.OnTimeTeam.OnTime.SMARTALARM");
										
										//save all alarm features in the intent in order to present to user in the next screen
										newAlarmIntent.putExtra("label", alarmsArray.get(reminderIndex).getLabel());
										newAlarmIntent.putExtra("index", alarmsArray.get(reminderIndex).getIndex());
										newAlarmIntent.putExtra("id", alarmsArray.get(reminderIndex).getID());
										newAlarmIntent.putExtra("days", alarmsArray.get(reminderIndex).getDaysToRepeat());
										newAlarmIntent.putExtra("daysIDS", alarmsArray.get(reminderIndex).getDaysIDS());
										newAlarmIntent.putExtra("hour", alarmsArray.get(reminderIndex).getHour());
										newAlarmIntent.putExtra("minute", alarmsArray.get(reminderIndex).getMinute());
									
										newAlarmIntent.putExtra("vibration", alarmsArray.get(reminderIndex).getVibration());
										newAlarmIntent.putExtra("volume", alarmsArray.get(reminderIndex).getVolume());
										newAlarmIntent.putExtra("snoozeInterval", alarmsArray.get(reminderIndex).getSnoozeInterval());
										newAlarmIntent.putExtra("snoozeRepeat", alarmsArray.get(reminderIndex).getSnoozeRepeat());
										newAlarmIntent.putExtra("tune", alarmsArray.get(reminderIndex).getTune());
										
										//set specal features
										newAlarmIntent.putExtra("origin", ((SmartAlarmFeatures)alarmsArray.get(reminderIndex)).getOrigin());
										newAlarmIntent.putExtra("destination", ((SmartAlarmFeatures)alarmsArray.get(reminderIndex)).getDest());
										newAlarmIntent.putExtra("tto",((SmartAlarmFeatures)alarmsArray.get(reminderIndex)).getTTO());
										newAlarmIntent.putExtra("transport",((SmartAlarmFeatures)alarmsArray.get(reminderIndex)).getTransport());
										
										newAlarmIntent.putExtra("arrivalHour",((SmartAlarmFeatures)alarmsArray.get(reminderIndex)).getArrivalHour());
										newAlarmIntent.putExtra("arrivalMinute",((SmartAlarmFeatures)alarmsArray.get(reminderIndex)).getArrivalMinute());
										
										//put boolean value to tell SetNewAlarm activity we want edit an existing alarm
										newAlarmIntent.putExtra("isNewAlarm", false);
										//start the activity which creates the alarm
										finish();
										startActivity(newAlarmIntent);
										overridePendingTransition(R.anim.grow_from_top, R.anim.fade_out);
									}
									else {
										textMessage.setText(getResources().getString(R.string.verifyNetworkConnection));
										toast.show();										}
								}
								else {
									
									final int i = reminderIndex;
									
									final LayoutInflater inflater = (LayoutInflater) RemindersCollection.this.getSystemService(LAYOUT_INFLATER_SERVICE);
									
									View quickLayout = inflater.inflate(R.layout.quick_nap_time_picker, null);
									quickNapMins = (TextView)quickLayout.findViewById(R.id.minutes);
									quickNapTimePicker = (SeekBar)quickLayout.findViewById(R.id.ttoSeekBar);

									Button saveButton = (Button)quickLayout.findViewById(R.id.bSave);
									Button cancelButton = (Button)quickLayout.findViewById(R.id.bCancel);

									final Dialog quickNapDialog = new Dialog(RemindersCollection.this, R.style.GrowBottom);
									quickNapDialog.setContentView(quickLayout);
									quickNapDialog.setCancelable(true);
									quickNapDialog.setTitle(getResources().getString(R.string.quickButton));
									
									
									cancelButton.setOnClickListener(new View.OnClickListener() {
										public void onClick(View v) {
											quickNapDialog.dismiss();
										}
									});
									
									saveButton.setOnClickListener(new View.OnClickListener() {
										public void onClick(View v) {
											
											SetQuickNap.updateWithNewTime(alarmsArray.get(i), quickNapTimePicker.getProgress()+3, getApplicationContext(),i);
											
								            Intent notifyService = new Intent("com.OnTimeTeam.OnTime.NotificationService");
								            startService(notifyService);
											
								            adapter.notifyDataSetChanged();
											
								            setTimeToNextAlarm();
								            
			                            	//restart the activity in order to refresh alarms-list
			                            	//Intent savedIntent = new Intent(RemindersCollection.this, MainActivity.class);
			                            	//finish();
			                            	quickNapDialog.dismiss(); //Dismiss the dialog box
			                            	//startActivity(savedIntent);
										}
									});


									
									quickNapMins.setText(alarmsArray.get(reminderIndex).getQuickInterval() + " " + getResources().getString(R.string.minutes));
									

									quickNapTimePicker.setMax(57);
									quickNapTimePicker.setProgress(Integer.valueOf(alarmsArray.get(reminderIndex).getQuickInterval())-3);
									quickNapTimePicker.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
										
								        public void onStopTrackingTouch(SeekBar seekBar) {
								        }

								        public void onStartTrackingTouch(SeekBar seekBar) {
								        }

								        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
								        	
								        	quickNapMins.setText(Integer.toString(progress + 3) + " " + getResources().getString(R.string.minutes));

								        }
								    });

									quickNapDialog.show();

								}
								
								break;
							case 2:
								deleteAlarm(reminderIndex);
								break;
							case 3:
								
				        		final Intent intent = new Intent(getBaseContext(), RouteDetailsTabHost.class);
				        		intent.putExtra("ArrivalHour", ((SmartAlarmFeatures)alarmsArray.get(reminderIndex)).getArrivalHour());
				        		intent.putExtra("ArrivalMinute", ((SmartAlarmFeatures)alarmsArray.get(reminderIndex)).getArrivalMinute());
				        		intent.putExtra("Hour", ((SmartAlarmFeatures)alarmsArray.get(reminderIndex)).getHour());
				        		intent.putExtra("Minute", ((SmartAlarmFeatures)alarmsArray.get(reminderIndex)).getMinute());
				        		intent.putExtra("Origin", ((SmartAlarmFeatures)alarmsArray.get(reminderIndex)).getOrigin());
				        		intent.putExtra("Dest", ((SmartAlarmFeatures)alarmsArray.get(reminderIndex)).getDest());
				        		intent.putExtra("TTO", ((SmartAlarmFeatures)alarmsArray.get(reminderIndex)).getTTO());
				        		intent.putExtra("Transport", ((SmartAlarmFeatures)alarmsArray.get(reminderIndex)).getTransport());
				        		
				        		if(((SmartAlarmFeatures)alarmsArray.get(reminderIndex)).getTransport().equals("Transit"))
				        		{
				        			intent.putExtra("track",((SmartAlarmFeatures)alarmsArray.get(reminderIndex)).getTrack());
				        			intent.putExtra("duration", ((SmartAlarmFeatures)alarmsArray.get(reminderIndex)).getDuration());
				        			intent.putExtra("distance", ((SmartAlarmFeatures)alarmsArray.get(reminderIndex)).getDistance());
				        		}
				        		
				        		startActivity(intent);
								break;
							case 4:
								
							try {
								
								String origin = URLEncoder.encode(((SmartAlarmFeatures)alarmsArray.get(reminderIndex)).getOrigin(), "UTF-8");
								String dest = URLEncoder.encode(((SmartAlarmFeatures)alarmsArray.get(reminderIndex)).getDest(), "UTF-8");
								
								if(((SmartAlarmFeatures)alarmsArray.get(reminderIndex)).getTransport().equals("Vehicle")) {
									startActivity(new Intent(android.content.Intent.ACTION_VIEW, 
										    Uri.parse("http://maps.google.com/maps?saddr=" + origin + "&daddr=" + dest + "&dirflg=d")));
								}
								else if (((SmartAlarmFeatures)alarmsArray.get(reminderIndex)).getTransport().equals("Transit") == false) {
									startActivity(new Intent(android.content.Intent.ACTION_VIEW, 
										    Uri.parse("http://maps.google.com/maps?saddr=" + origin + "&daddr=" + dest + "&dirflg=w")));
								}
								else	
								{
									startActivity(new Intent(android.content.Intent.ACTION_VIEW, 
										    Uri.parse("http://maps.google.com/maps?saddr=" + origin + "&daddr=" + dest + "&dirflg=r")));

								}
							} catch (UnsupportedEncodingException e) {
								e.printStackTrace();
							}
								

								break;
						}
						dialog.dismiss();
					}
				});
						
				//create adapter for the list
				ReminderOptionsAdapter reminderOptionsAdapter = new ReminderOptionsAdapter(RemindersCollection.this, R.layout.regular_alarm_item, items, alarmsArray.get(reminderIndex).getStatus(), alarmsArray.get(reminderIndex).getSortOfAlarm());
				optionsList.setAdapter(reminderOptionsAdapter);
				optionsList.setTextFilterEnabled(true);
	 
				dialog.show();
				     	
				return false;
			}
		});
		
	}//EO-onCreate method

	public boolean onKeyDown(int keyCode, KeyEvent event) {
	    if (keyCode == KeyEvent.KEYCODE_BACK) {
	    	
	    	backPressed+=1;
			
			if(backPressed == 1) {
				textMessage.setText(getResources().getString(R.string.pressBack));
				toast.show();				
			}
			else if(backPressed == 2)
				onBackPressed();

			new java.util.Timer().schedule( 
			        new java.util.TimerTask() {
			            public void run() {
			            	backPressed = 0;
			            }
			        }, 
			        2000 
			);
			
	        return true;
	    }
	    return super.onKeyDown(keyCode, event);
	}
	

	/*Everything that happens within these brackets, happens when the activity is destroyed.*/
	protected void onDestroy() {
		super.onDestroy();
	}

	
	protected void onResume() {
		super.onResume();
	}

	protected void onPause() {
		super.onPause();
	}
	
	private boolean isNetworkAvailable() {
	    ConnectivityManager connectivityManager 
	          = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
	    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
	    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
	}
	
	public void updateAlarmsAfterAddition(AlarmFeatures af){
		
		alarmsArray.add(0, af);
		adapter.addQuickItemOnStart("QUICK_ITEM");
		
        Intent notifyService = new Intent("com.OnTimeTeam.OnTime.NotificationService");
        startService(notifyService);
        
        setTimeToNextAlarm();
        
	}
		
		
		
	public void setTimeToNextAlarm(){
		
		Animation myFadeInAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_in);

		
		ArrayList<AlarmFeatures> alarmsOn = new ArrayList<AlarmFeatures>();
		
        for(int i = 0; i < alarmsArray.size(); ++i)
        	if(alarmsArray.get(i).getStatus().equals("On"))
        		alarmsOn.add(alarmsArray.get(i));
        
        if(alarmsOn.size() > 0) {
        	String notification = NotificationService.getClosestAlarmString(alarmsOn, remindersFilePath);
        	notification = notification.replace("Next alarm set for", getResources().getString(R.string.nextAlarmSetFor));
        	notification = notification.replace("Sun,", getResources().getString(R.string.sunQ));
        	notification = notification.replace("Mon,", getResources().getString(R.string.monQ));
        	notification = notification.replace("Tue,", getResources().getString(R.string.tueQ));
        	notification = notification.replace("Wed,", getResources().getString(R.string.wedQ));
        	notification = notification.replace("Thu,", getResources().getString(R.string.thuQ));
        	notification = notification.replace("Fri,", getResources().getString(R.string.friQ));
        	notification = notification.replace("Sat,", getResources().getString(R.string.satQ));
        	notification = notification.replace("Today,", getResources().getString(R.string.todayQ));

        	if(!notification.equals(timeToNextAlarm.getText().toString())){
	        	timeToNextAlarm.setText(notification);
	        	timeToNextAlarm.setVisibility(View.VISIBLE);
	        	timeToNextAlarm.startAnimation(myFadeInAnimation);
        	}
        }
        else {
        	timeToNextAlarm.setText("");
        	timeToNextAlarm.setVisibility(View.GONE);
        }
	}
	
	//Delete an alarm from the alarms list, files and system - and refresh UI
	void deleteAlarm(int reminderIndex){
		
		//First cancel snooze
		String snoozeID = RemindersIO.getSnoozeAlarmSign(alarmsArray.get(reminderIndex).getID(), remindersFilePath).split(",")[0];
		if(!snoozeID.equals("None")) {
			AlarmFeatures tmpAF = new AlarmFeatures();
			tmpAF.setDaysIDS(snoozeID);
			AlarmSetter.cancelExistingAlarm(tmpAF, getApplicationContext());
		}
		
		//Then cancel alarm
		AlarmSetter.cancelExistingAlarm(alarmsArray.get(reminderIndex), getApplicationContext());
		
		//Delete from files
		RemindersIO.deleteAlarm(remindersFilePath, Integer.toString(reminderIndex));
		
		//Remove the item from alarms array
		alarmsArray.remove(reminderIndex);
		
		//Remove the item from the list
		adapter.removeItem(reminderIndex);
		
		//Update StatusBar
        startService(new Intent("com.OnTimeTeam.OnTime.NotificationService"));
        setTimeToNextAlarm();
	}
		
}//EOF

